<template>
  <div class="snack-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>零食管理</span>
          <div class="search-container">
            <el-input
              v-model="searchName"
              placeholder="搜索名称"
              style="width: 200px"
              clearable
              @clear="handleSearch"
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            
            <el-input-number
              v-model="minPrice"
              placeholder="最低价格"
              :min="0"
              :precision="2"
              style="width: 130px"
              @change="handleSearch"
            />
            <el-input-number
              v-model="maxPrice"
              placeholder="最高价格"
              :min="0"
              :precision="2"
              style="width: 130px"
              @change="handleSearch"
            />
            
            <el-input-number
              v-model="minStock"
              placeholder="最低库存"
              :min="0"
              style="width: 130px"
              @change="handleSearch"
            />
            <el-input-number
              v-model="maxStock"
              placeholder="最高库存"
              :min="0"
              style="width: 130px"
              @change="handleSearch"
            />
            
            <el-select 
              v-model="searchStatus" 
              placeholder="状态" 
              style="width: 120px; margin-right: 10px"
              clearable
              @change="handleSearch"
            >
              <el-option label="下架" :value="0" />
              <el-option label="上架" :value="1" />
            </el-select>
            
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button type="success" @click="handleAdd">新增零食</el-button>
          </div>
        </div>
      </template>

      <el-table :data="snacks.records" style="width: 100%" v-loading="loading">
        <el-table-column prop="name" label="名称" />
        <el-table-column prop="price" label="价格" width="100">
          <template #default="scope">
            ¥{{ scope.row.price.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="stock" label="库存" width="100" />
        <el-table-column prop="description" label="描述" show-overflow-tooltip />
        <el-table-column prop="createdAt" label="创建时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
              {{ scope.row.status === 1 ? '上架' : '下架' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="图片" width="100">
          <template #default="scope">
            <el-image
              v-if="scope.row.imageUrl"
              :src="getImageUrl(scope.row.imageUrl)"
              :preview-src-list="[getImageUrl(scope.row.imageUrl)]"
              fit="cover"
              style="width: 50px; height: 50px"
            />
            <span v-else>无图片</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button 
              type="primary" 
              size="small" 
              @click="handleEdit(scope.row)"
            >
              编辑
            </el-button>
            <el-button 
              :type="scope.row.status === 1 ? 'warning' : 'success'"
              size="small" 
              @click="handleToggleStatus(scope.row)"
            >
              {{ scope.row.status === 1 ? '下架' : '上架' }}
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="snacks.total || 0"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="form.id ? '编辑零食' : '新增零食'"
      width="500px"
      @close="handleDialogClose"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number 
            v-model="form.price" 
            :min="0" 
            :precision="2" 
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="库存" prop="stock">
          <el-input-number 
            v-model="form.stock" 
            :min="0" 
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="图片" prop="imageUrl">
          <el-upload
            class="snack-uploader"
            :action="uploadUrl"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :before-upload="beforeUpload"
            :headers="headers"
            accept="image/*"
            :multiple="false"
            name="file"
          >
            <img v-if="form.imageUrl" :src="form.imageUrl" class="uploaded-image">
            <div v-else class="upload-placeholder">
              <el-icon class="uploader-icon"><Plus /></el-icon>
              <div class="upload-text">点击上传图片</div>
            </div>
          </el-upload>
          <div class="upload-tip">支持 jpg、png 格式，大小不超过 2MB</div>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input type="textarea" v-model="form.description" :rows="4" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus } from '@element-plus/icons-vue'
import request from '@/utils/request'
import { formatDateTime } from '@/utils/dateUtil'
import { useUserStore } from '@/stores/user'

const userStore = useUserStore()
const baseUrl = '/api'
const uploadUrl = `${baseUrl}/admin/snacks/upload`
const headers = {
  Authorization: `Bearer ${userStore.token}`
}

const loading = ref(false)
const submitLoading = ref(false)
const snacks = ref({ records: [], total: 0 })
const dialogVisible = ref(false)
const formRef = ref(null)
const searchName = ref('')
const searchStatus = ref('')
const minPrice = ref(null)
const maxPrice = ref(null)
const minStock = ref(null)
const maxStock = ref(null)
const currentPage = ref(1)
const pageSize = ref(10)

const form = reactive({
  id: '',
  name: '',
  price: 0,
  stock: 0,
  description: '',
  status: 0,
  imageUrl: ''
})

const rules = {
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  price: [{ required: true, message: '请输入价格', trigger: 'blur' }],
  stock: [{ required: true, message: '请输入库存', trigger: 'blur' }],
  imageUrl: [{ 
    required: true, 
    message: '请上传图片', 
    trigger: 'change',
    validator: (rule, value, callback) => {
      if (!form.imageUrl) {
        callback(new Error('请上传图片'))
      } else {
        callback()
      }
    }
  }]
}

const formatDate = (date) => {
  if (!date) return '-';
  
  try {
    // 处理数组格式的日期 [YYYY, M, DD, HH, mm, ss]
    if (Array.isArray(date)) {
      // 确保数组有足够的元素
      if (date.length >= 6) {
        const [year, month, day, hour, minute, second] = date;
        // 月份需要格式化为两位数
        const formattedMonth = String(month).padStart(2, '0');
        const formattedDay = String(day).padStart(2, '0');
        const formattedHour = String(hour).padStart(2, '0');
        const formattedMinute = String(minute).padStart(2, '0');
        const formattedSecond = String(second).padStart(2, '0');
        
        return `${year}-${formattedMonth}-${formattedDay} ${formattedHour}:${formattedMinute}:${formattedSecond}`;
      }
      // 如果数组格式不完整，则返回原始值
      return JSON.stringify(date);
    }
    
    // 尝试常规日期格式
    const dateObj = new Date(date);
    if (!isNaN(dateObj.getTime())) {
      const year = dateObj.getFullYear();
      const month = String(dateObj.getMonth() + 1).padStart(2, '0');
      const day = String(dateObj.getDate()).padStart(2, '0');
      const hours = String(dateObj.getHours()).padStart(2, '0');
      const minutes = String(dateObj.getMinutes()).padStart(2, '0');
      const seconds = String(dateObj.getSeconds()).padStart(2, '0');
      
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    }
    
    // 如果既不是数组也不是有效日期，则返回原始值
    return date;
  } catch (error) {
    console.error('日期格式化错误:', error);
    return date; // 发生错误时返回原始值
  }
}

const loadSnacks = async () => {
  try {
    loading.value = true
    const res = await request.get('/admin/snacks', {
      params: {
        current: currentPage.value,
        size: pageSize.value,
        name: searchName.value || null,
        minPrice: minPrice.value || null,
        maxPrice: maxPrice.value || null,
        minStock: minStock.value || null,
        maxStock: maxStock.value || null,
        status: searchStatus.value !== undefined && searchStatus.value !== '' 
          ? (searchStatus.value === 0 ? 1 : 0) 
          : null
      }
    })
    if (res.code === 200) {
      snacks.value = res.data
    }
  } catch (error) {
    console.error('Failed to load snacks:', error)
    ElMessage.error('加载零食列表失败')
  } finally {
    loading.value = false
  }
}

const handleAdd = () => {
  dialogVisible.value = true
  Object.assign(form, {
    id: '',
    name: '',
    price: 0,
    stock: 0,
    description: '',
    status: 0,
    imageUrl: ''
  })
}

const handleEdit = (row) => {
  dialogVisible.value = true
  Object.assign(form, row)
}

const handleToggleStatus = (row) => {
  const newStatus = row.status === 1 ? 0 : 1
  const actionText = newStatus === 1 ? '上架' : '下架'
  
  ElMessageBox.confirm(`确定要${actionText}该零食吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await request.put(`/admin/snacks/${row.id}/status`, { status: newStatus })
      ElMessage.success(`${actionText}成功`)
      loadSnacks()
    } catch (error) {
      console.error('Failed to update snack status:', error)
      ElMessage.error('操作失败')
    }
  }).catch(() => {
    // 用户取消操作
  })
}

const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该零食吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await request.delete(`/admin/snacks/${row.id}`)
      ElMessage.success('删除成功')
      loadSnacks()
    } catch (error) {
      console.error('Failed to delete snack:', error)
    }
  })
}

const handleDialogClose = () => {
  formRef.value?.resetFields()
}

const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

const handleUploadError = (error) => {
  console.error('Upload error:', error)
  ElMessage.error('图片上传失败，请重试')
  form.imageUrl = ''
}

const getImageUrl = (path) => {
  if (!path) return ''
  if (path.startsWith('http')) return path
  return path.startsWith('/') ? `/api${path}` : `/api/${path}`
}

const handleUploadSuccess = (res) => {
  console.log('Upload response:', res)
  if (res.code === 200) {
    form.imageUrl = getImageUrl(res.data)
    ElMessage.success('上传成功')
  } else {
    ElMessage.error(res.msg || '上传失败')
    form.imageUrl = ''
  }
}

const handleSubmit = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        submitLoading.value = true
        const submitData = {
          ...form,
          imageUrl: form.imageUrl.replace('/api', '')
        }
        
        if (form.id) {
          await request.put(`/admin/snacks/${form.id}`, submitData)
        } else {
          await request.post('/admin/snacks', submitData)
        }
        ElMessage.success(form.id ? '编辑成功' : '新增成功')
        dialogVisible.value = false
        loadSnacks()
      } catch (error) {
        console.error('Failed to submit:', error)
        ElMessage.error('操作失败')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

const handleSearch = () => {
  currentPage.value = 1
  loadSnacks()
}

const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  loadSnacks()
}

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage
  loadSnacks()
}

loadSnacks()
</script>

<style scoped>
.snack-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-container {
  display: flex;
  align-items: center;
  gap: 10px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.snack-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
  display: flex;
  justify-content: center;
  align-items: center;
  transition: border-color 0.3s;
}

.snack-uploader:hover {
  border-color: #409EFF;
}

.upload-placeholder {
  text-align: center;
}

.uploader-icon {
  font-size: 28px;
  color: #8c939d;
  margin-bottom: 8px;
}

.upload-text {
  color: #8c939d;
  font-size: 12px;
}

.uploaded-image {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.upload-tip {
  color: #909399;
  font-size: 12px;
  margin-top: 5px;
  line-height: 1.2;
}

.snack-uploader.is-loading {
  cursor: not-allowed;
  opacity: 0.7;
}
</style> 